/**
 * index for git helper
 *
 * @author: koradji
 * @date: 2024/12/27
 */
(function () {
    const NWIN = "_githelper";

    var draggableWindow = null;
    var draggableWindowEnabled = false;
    var data = [];

    class GitHelper {

        // 初始化助手
        init(params) {
            data = params;
            let button = document.createElement("button")
            button.textContent = "助手"
            button.type = "input"
            button.addEventListener("click", this.initHelperWindow); // 设置点击助手事件
            let li = document.createElement("li")
            li.appendChild(button)
            document.getElementsByClassName("navbar-sub-nav")[0].appendChild(li);
        }

        // 1. 初始化弹窗
        initHelperWindow() {
            if (draggableWindow == null) {
                const header = document.createElement("div");
                header.className = "git_helper_header";
                header.id = "draggableWindow_header";

                const leftDiv = document.createElement("div");
                leftDiv.setAttribute("style", "float: left; font-weight: bold")
                leftDiv.textContent = "git helper";
                header.appendChild(leftDiv);

                const rightDiv = document.createElement("div");
                rightDiv.setAttribute("style", "float: right; font-weight: bold")
                header.appendChild(rightDiv);

                const centerDiv = document.createElement("div");
                header.appendChild(centerDiv);

                const xxxHtml =
                    '<a data-qa-selector="dropdown-menu frequent-items-dropdown-menu" data-toggle="dropdown" href="#" aria-expanded="false">' +
                    '&nbsp;&nbsp;更多' +
                    '<svg class="caret-down"><use xlink:href="/assets/icons-730bc9dd942fde159bc545aaf03f0f828f24a8a4cf2cf3c95c9d5b3042a98e0d.svg#angle-down"></use></svg>' +
                    '</a>' +
                    '<div class="dropdown-menu" x-placement="bottom-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(295px, 26px, 0px);">' +
                    '<ul id="prods">' +
                    '</ul>';
                centerDiv.innerHTML = xxxHtml;

                const hideButton = document.createElement("button");
                hideButton.id = "hideButton";
                hideButton.setAttribute("style", "border: none; background: rgba(0,0,0,0); font-weight: normal");
                hideButton.addEventListener("mouseover", (e) => e.target.style.fontWeight = "bold");
                hideButton.addEventListener("mouseout", (e) => e.target.style.fontWeight = "normal");
                hideButton.textContent = "x";
                hideButton.setAttribute("type", "input");
                hideButton.addEventListener("click", function () {
                    draggableWindowEnabled = !draggableWindowEnabled;
                    draggableWindow.hidden = draggableWindowEnabled
                })
                rightDiv.appendChild(hideButton);

                const content = document.createElement("div");
                content.setAttribute("id", "xflib-content")
                content.className = "git_helper_content";

                draggableWindow = document.createElement("div");
                draggableWindow.className = 'git_helper_window';
                draggableWindow.appendChild(header);
                draggableWindow.appendChild(content);

                document.body.appendChild(draggableWindow);
                draggableWindow.setAttribute("id", "draggableWindow");
                draggableWindow.setAttribute("style", "left: 100px; top: 40px");

                // 2. 初始化拖拽状态
                gitHelper.dragElement(draggableWindow);

                // 3. 初始化动态内容
                gitHelper.initContent(content);

            } else {
                draggableWindowEnabled = !draggableWindowEnabled;
                draggableWindow.hidden = draggableWindowEnabled;
            }
        }

        // 初始化弹窗内的动态内容
        initContent(container) {

            // 初始化操作
            let contentAll = "";

            // 按分组
            data.categories.forEach(category=>{
                let content = gitHelper.getContent(data.projects.filter(t=>t.category===category.code), category);
                if (content.content.length > 0) contentAll = contentAll + content.content;
            });
            container.innerHTML = contentAll;
            
            // 4. 初始化操作点击事件
            for (var x of document.getElementsByClassName("git_helper_opClass")) {
                x.addEventListener("click", gitHelper.opration);
            }

            // 5. 初始化产品列表
            const prodEle = document.getElementById("prods");
            let _innerHtml = "";
            data.products.forEach(t => {
                _innerHtml = _innerHtml + '<li><a class="dashboard-shortcuts-groups" href="' + t.home + '">' + t.name + '</a></li>'
            })
            prodEle.innerHTML = _innerHtml;
        }

        // 按项目
        getContent(projects, category) {
            let content = "";
            projects/*.filter(t => category == category)*/.forEach(function (item, index, projects) {
                content = content + '<li><span onmouseover="this.style.borderBottom=\'1px solid #000\'" onmouseout="this.style.borderBottom=\'none\'">' +
                    '<a href="' + item.url + '"target=' + NWIN +
                    '><span style="display:inline-block; width: 170px; font-weight: bold">' + item.name + '</span></a>';
                const operations = Array.isArray(item.permissions)?item.permissions:item.permissions.split(",")
                operations.forEach(op => {
                    content = content + '<button type=input' +
                        ' data="' + item.url + '"' +
                        ' class="git_helper_opClass" style="border: none; background: rgba(0,0,0,0)"' +
                        ' onmouseover="this.style.fontWeight=\'bold\'"' +
                        ' onmouseout="this.style.fontWeight=\'normal\'"' +
                        ' op="' + data.config.operations[op].path + '"' +
                        '>' + data.config.operations[op].name + '</button>'
                })
                content = content + '</spane></li>';
            });
            if (content.length > 0) content = "<div>" + category.name + "<ul style=\"margin-bottom: 0\">" + content + "</ul></div>";
            return {"content": content, group: {code: category.code, title: category.name}};
        }

        // 弹窗拖拽事件
        dragElement(elmnt) {
            var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            if (document.getElementById(elmnt.id + "_header")) {
                /* 如果存在，header 就是你移动 DIV 的地方：*/
                document.getElementById(elmnt.id + "_header").onmousedown = dragMouseDown;
            } else {
                /* 否则，将 DIV 从 DIV 内的任何位置移动：*/
                elmnt.onmousedown = dragMouseDown;
            }

            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                // 在启动时获取鼠标光标位置：
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                // 当光标移动时调用一个函数：
                document.onmousemove = elementDrag;
            }

            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                // 计算新的光标位置：
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                // 设置元素的新位置：
                elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
            }

            function closeDragElement() {
                /* 释放鼠标按钮时停止移动：*/
                document.onmouseup = null;
                document.onmousemove = null;
            }
        }

        // 点击模块事件
        opration(e) {
            let home = e.currentTarget.getAttribute("data");
            let op = e.currentTarget.getAttribute("op");
            if (op == "edit") {
                window.open(home + op, NWIN)
            } else {
                window.open(home + op, NWIN)
            }
        }

    }

    parseUrl = (url) => {
        const urlObj = new URL(url);
        const pathParts = urlObj.pathname.replace(/^\//, '').split('/');
        return {
            home: urlObj.origin.concat("/",pathParts[0]||''), 
            product: pathParts[0]||'',
            module: pathParts[1]||'',
            category: pathParts[pathParts.length-1]||'',
            partialUrl: urlObj.pathname.replace(/^\//, '')||''
        };
    }

    gitHelper = new GitHelper();

    try {
        chrome.runtime.sendMessage({
            "product": "git-helper"
            , "domain": "storage.local"
            , "action": "get"
            , "data": ["projects","categories","products"]
        }, response=> {
            const projects= Object.entries(response.data.projects)
                .filter(([code, project]) => project.productCode == this.parseUrl(window.location).product)
                .map(([code, project]) => ({code, ...project}));
                const home = parseUrl(projects[0].url).home;
                gitHelper.init({
                    config: {
                        operations: {
                            "branches": {path: "/-/branches", name:"分支"},
                            "tags":{path: "/-/tags", name: "标签"},
                            "members":{path: "/-/project_members", name: "成员"},
                            "repository":{path: "/-/settings/repository", name: "仓库"},
                            "edit":{path: "/-/edit",name: "项目"},
                            "commits":{path: "/-/commits", name: "提交"}
                        }
                    },
                    projects: projects,
                    categories: [...Object.entries(response.data.categories)].filter(t=>[...new Set(projects.map(project=>project.category))].includes(t[0])).map(([key, value])=>({code:key,name:value})),
                    products: [...Object.entries(response.data.products)].filter(([product,_])=>[...new Set(projects.map(project=>project.productCode))].includes(product)).map(([key, value])=>({code:key, name:value, home:home}))
            })
        })
        .catch(()=>{alert("读取数据出现了错误，请检查设置!")});
    } catch (e) {
        console.log("githelper.afterInit error: ", e)
    }
})();